package com.doctcloud.hisinfo.api.factory;

import com.doctcloud.common.core.domain.R;
import com.doctcloud.hisinfo.api.RemoteHisMedrecService;
import com.doctcloud.hisinfo.histable.domain.medrec.PatMasterIndexDo;
import com.doctcloud.hisinfo.histable.domain.medrec.PatVisitDo;
import com.doctcloud.hisinfo.histable.domain.medrec.TransferDo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.openfeign.FallbackFactory;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.Date;
import java.util.List;

import static com.doctcloud.common.core.utils.DateUtils.formatFullDateWithTime;

@Component
public class RemoteHisMedrecFallbackFactory implements FallbackFactory<RemoteHisMedrecService> {
    private static final Logger log = LoggerFactory.getLogger(RemoteHisMedrecFallbackFactory.class);
    @Override
    public RemoteHisMedrecService create(Throwable cause) {
        return new RemoteHisMedrecService() {
            @Override
            public R<PatMasterIndexDo> getPatMasterIndexById(String patientId) {
                return R.fail("获取患者ID主记录失败:" + cause.getMessage());
            }

            @Override
            public R<List<PatMasterIndexDo>> getPatMasterIndexByIds(List<String> patientIds) {
                return R.fail("获取患者IDs主记录失败:" + cause.getMessage());
            }

            @Override
            public List<TransferDo> listTransferByPat(String patientId, Integer visitId) {
                // 为这次具体的失败调用记录详细日志，方便排查
                String errorMessage = String.format("获取患者ID:[%s], 住院标识:[%s] 的转科信息失败，服务已降级。", patientId, visitId);
                log.error(errorMessage);

                // 返回一个空的、不可变的列表，这是方案一推荐的做法
                // 调用方收到空列表后，会认为没有数据需要同步，从而自然结束流程
                return Collections.emptyList();
            }

            @Override
            public List<PatVisitDo> adminAfterDate(Date staticDate) {
                String errorMessage = String.format("获取患者住院记录:[%s]之后信息失败，服务已降级。", formatFullDateWithTime(staticDate));
                log.error(errorMessage);
                return Collections.emptyList();
            }

            @Override
            public List<PatVisitDo> dischargeAfterDate(Date staticDate) {
                String errorMessage = String.format("获取患者出院记录:[%s]之后信息失败，服务已降级。", formatFullDateWithTime(staticDate));
                log.error(errorMessage);
                return Collections.emptyList();
            }
        };
    }
}
